<template>
	<div class="outgoing" v-if="show">

		<span class="down-execel">
			<Poptip v-model="showFilter" placement="bottom-end">
				<i class="el-icon-search poptip-condition-add"></i>
				<a href="javascript:;" class='poptip-condition-add'>列表查找</a>
				<div slot="content">
					<Poptip v-model="showFilterCondition" placement="bottom-start" class='poptip-condition'>
						<i class="el-icon-plus"></i>
						<!-- <a href="javascript:;" @click='getAllAgent'>添加过滤条件</a> -->
						<a href="javascript:;">添加过滤条件</a>

						<div slot="content" class="condition-list">
							<ul>
								<li v-for="(item, index) in columns" class='poptip-condition-item' @click="addFilterCondition(item)" :key="index">{{item.label}}</li>
							</ul>
						</div>
					</Poptip>

					<el-form :model="conditionForm" ref="conditionForm" label-width="120px" class="demo-dynamic" @submit.native.prevent>
						<el-form-item v-for="(condition, index) in conditionForm.condition" :label="condition.label" :key="condition.key"
						 :prop="'condition.' + index + '.value'" :rules="{
                  required: true, message: condition.label + '不能为空', trigger: 'blur'
              }">
								<el-date-picker
									v-model="submitTime"
									type="daterange"
									placeholder="选择日期"
									value-format="yyyy-MM-dd"
									size="small"
									:validate-event='false'
									@input = 'changInput'
									v-if='condition.label === "注册时间"'>
								</el-date-picker>

                <el-date-picker
									v-model="updateTime"
									type="daterange"
									placeholder="选择日期"
									value-format="yyyy-MM-dd"
									size="small"
									:validate-event='false'
									@input = 'changInput'
									v-else-if='condition.label === "离职时间"'>
								</el-date-picker>

                <el-input v-else size="small" v-model="condition.value" @keyup.enter.native="submitsearch('conditionForm')"></el-input>
							<el-button @click.stop="removeDomain(condition)" size="mini">删除</el-button>
						</el-form-item>
					</el-form>

					<div class="btns">
						<el-button @click="submitsearch('conditionForm')" size="mini">查询</el-button>
						<el-button @click="resetForm('conditionForm')" size="mini">重置</el-button>
					</div>
				</div>
			</Poptip>
		</span>
		<span class="down-execel" @click="exportExcel('离职人员表')">
      <i class="el-icon-download"></i> <a href="javascript:;">导出列表</a>
    </span>

		<el-table
			id="IMTable"
			:data="tableData"
			border
			style="width: 100%"
		 	v-loading="loading"
			ref="multipleTable"
			height="88%"
			@sort-change='tableSortChange'
			tooltip-effect="dark">
			<el-table-column show-overflow-tooltip prop="id" label="ID" width="60" align="left">
				<template slot-scope="scope">{{(scope.$index+1)+(currentPage-1)*tableSize}}</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip prop="name" label="姓名" width="120" align="left" sortable='custom'></el-table-column>
			<el-table-column show-overflow-tooltip prop="type" label="职别" width="120" align="left" sortable='custom'>
				<template slot-scope="scope">
					{{ scope.row.role.display_name }}
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip prop="phone" label="手机号码"  width="180" align="left" sortable='custom'></el-table-column>
			<el-table-column show-overflow-tooltip prop="email" label="个人邮箱" align="left" width="250" sortable='custom'></el-table-column>
			<el-table-column show-overflow-tooltip prop="email_work" label="原邮箱" width="250" align="left" sortable='custom'></el-table-column>
			<el-table-column show-overflow-tooltip label="在职时间(月)" align="left" prop="created_at" sortable='custom' width="130">
				<template slot-scope="scope">
					{{ IncumbencyTime(scope.row.created_at ,scope.row.leaved_at) }}
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip prop="created_at" label="注册时间" width="220" align="left" sortable='custom'>
				<template slot-scope="scope">{{ scope.row.created_at | formatTime }}</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip prop="leaved_at" label="离职日期" width="220" align="left" sortable='custom'></el-table-column>
		</el-table>
		<!-- 分页 -->
		<el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
			:page-sizes="pageSizes" :page-size="Number(pageSize)" layout="total, sizes, prev, pager, next, jumper" :total="total"></el-pagination>

		<!-- 导出表格 -->
		<xy-excel-export-template ref="TerminalExportExcel"></xy-excel-export-template>
	</div>
</template>
<script>
	import {intervalTime} from '~/util'
	import {
		getOutGoing,
		delUser
	} from "~/api/user";
	import dialogAdd from "~/components/addUser";
	import dialogEdit from "~/components/editUser";
	import xyExcelExportTemplate from "~/components/ExcelExportTemplate";
	export default {
		head: {
			title: "离职人员管理"
		},
		name: "agent",
		data() {
			return {
				total: 0,
				show: true,
				dialogFormVisible: false,
				form: {
					reason: '',
					job_time: '',
					leave_job_at: ''
				},
				rules: {
					reason: [{
						required: true,
						message: '请输入离职原因',
						trigger: 'blur'
					}],
					job_time: [{
						required: true,
						message: '请输入在职天数',
						trigger: 'blur'
					}],
					leave_job_at: [{
						required: true,
						message: '请输入离职日期',
						trigger: 'blur'
					}]
				},
				loading: false,
				tableData: [],
				checkTable: [],
				tableSize: 10, //一页几条
				currentPage: 1, //目前在第几页
				pageSizes: [25, 50], //一页可以几
				showFilter: false, // 控制显示筛选条件
				showFilterCondition: false,
				conditionForm: {
					condition: []
				}, //筛选条件
				columns: [{
						label: '姓名',
						id: 1,
						parameter: 'name'
					},
					{
						label: '手机号',
						id: 2,
						parameter: 'phone'
					},
					{
						label: '工作邮箱',
						id: 4,
						parameter: 'email_work'
					},
					{
						label: '个人邮箱',
						id: 4,
						parameter: 'email'
					},
					{
          label: '注册时间',
          id: 6,
          parameter: 'submitTime'
					},
					{
						label: '离职时间',
						id: 7,
						parameter: 'updateTime'
					},
				],
				paramsByUser:{
					role_id: 2,
					type: "离职",
				},
				submitTime: [],
      	updateTime: []
			};
		},
		components: {
			dialogAdd,
			dialogEdit,
			xyExcelExportTemplate
		},
		async asyncData({
			$axios
		}) {
			let res = await getOutGoing($axios);
			let obj = {
				loading: false
			};
			if (res.data.code == 200) {
				obj.total = res.data.page.total;
				obj.tableData = res.data.data;
				obj.pageSize = obj.tableData.length;
				obj.tableSize = obj.tableData.length;
				obj.tableEnd = obj.tableData.length;
			}
			return obj;
		},
		methods: {
			//导出excel
			exportExcel(name) {
				let tabHandle = [
					"姓名",
					"职别",
					"手机号码",
					"个人邮箱",
					"原邮箱",
					"在职时间(月)",
					"注册时间",
					"离职时间",
				];
				let params = {
					allPage: 2
				}
				params = Object.assign({}, this.paramsByUser)
				params.status = '已激活'
				this.$axios.get('api/user/leaving', {
					params: params
				})
				.then(res => {
					if (res.data.code == '200') {
						if (this.tableData.length) {
								let exTableData = []
								let item = {}
								for (let i in JSON.parse(JSON.stringify(this.tableData))) {
									item = this.tableData[i]
									exTableData.push(item);
								}
								this.$refs.TerminalExportExcel.exportExcelOutgoing(name, tabHandle, exTableData);
							}
					} else {
						this.$message.error('服务器繁忙')
					}
				})
			},
			initData() {
				let that = this;
				getOutGoing(that.$axios)
					.then(res => {
						if (res.data.code == 200) {
							that.tableData = res.data.data
							that.total = res.data.page.total
							that.pageSize = res.data.page.per_page
							that.tableSize = res.data.page.per_page
							that.tableEnd = res.data.page.per_page
						}
					})
			},
			//选择一页几条
			handleSizeChange(size) {
				this.paramsByUser.perPage = size
				this.paramsByUser.page = 1
				getOutGoing(this.$axios, this.paramsByUser)
				.then(res => {
					if (res.data.code == 200) {
						this.tableData = res.data.data;
						this.total = res.data.page.total
						this.pageSize = res.data.page.per_page
						this.tableSize = res.data.page.per_page
						this.tableEnd = res.data.page.per_page
					}
				})
			},
			//选择第几页
			handleCurrentChange(currentPage) {
				this.currentPage = currentPage;
				let params = this.paramsByUser
				params.page = currentPage
				getOutGoing(this.$axios, params)
				.then(res => {
					if (res.data.code == 200) {
						this.tableData = res.data.data;
					}
				})
			},
			// 获取在职时间
			IncumbencyTime(leaved_at,created_at) {
				if (created_at && leaved_at) {
					leaved_at = leaved_at.replace(/-/g, "/");
					created_at = created_at.replace(/-/g, "/");
					var createTime = new Date(leaved_at);
					//获取当前的时间戳
					var nowTime = new Date(created_at);
					let processingTime = ''
					//获取处理时间戳
					let cha = nowTime - createTime;
					let day = 1000 * 60 * 60 * 24;
					var month = day * 30
					let year = month * 12

					let round2 = (cha / month).toFixed(2)
					processingTime = (Math.ceil(round2 * 10) / 10).toFixed(1)
					if (processingTime <= 0) {
						return '0.0'
					}  else {
						return processingTime;
					}

					// return processingTime;

				} else {
					return ''
				}

			},

			async search() {
				this.currentPage = 1
				for (let i = 0; i < this.conditionForm.condition.length; i++) {
					let a = this.conditionForm.condition[i].parameter
					this.paramsByUser[a] = this.conditionForm.condition[i].value

					if (this.conditionForm.condition[i].parameter === 'submitTime') {
          this.paramsByUser.created_start_time = this.submitTime[0]
          this.paramsByUser.created_end_time = this.submitTime[1]
					}
					if (this.conditionForm.condition[i].parameter === 'updateTime') {
						this.paramsByUser.leaved_start_time = this.updateTime[0]
						this.paramsByUser.leaved_end_time = this.updateTime[1]
					}
				}

				// 处理分页数据
				delete this.paramsByUser.page
				delete this.paramsByUser.updateTime

				// 处理排序状态
				delete this.paramsByUser.sort_str
				delete this.paramsByUser.sort_order
				this.$refs['multipleTable'].clearSort()

				this.$axios.get('api/user/leaving', {
					params: this.paramsByUser
				})
				.then(res => {
					if (res.data.code == '200') {
						this.tableData = res.data.data
						this.total = res.data.page.total
						this.showFilter = false
					} else {
						this.$message.error('服务器繁忙')
					}
				})
			},

			// 添加条件筛选
			addFilterCondition(item) {
				let filterItem = {
					value: '',
					label: item.label,
					parameter: item.parameter,
					key: Date.now()
				}

				if (this.conditionForm.condition.length > 0) {
					let conditionlabels = []
					for (let i = 0; i < this.conditionForm.condition.length; i++) {
						conditionlabels.push(this.conditionForm.condition[i].label)
					}
					let Check = conditionlabels.indexOf(item.label)
					Check == -1 ? this.conditionForm.condition.push(filterItem) : this.$message.error('请勿重复添加')
				} else {
					this.conditionForm.condition.push(filterItem)
				}

				this.showFilterCondition = false;
			},
			resetForm(formName) {
				this.$refs[formName].resetFields()
				this.$refs['multipleTable'].clearSort()
				this.conditionForm.condition.forEach(v => {
					if (v.value) {
						v.value = null
					}
				});
				this.showFilterCondition = false
				this.submitTime = []
      			this.updateTime = []
				this.paramsByUser = {
					role_id: 2,
					type: "离职",
				}
				this.$nextTick(() => {
					this.$refs[formName].clearValidate()
				})
				// this.initData()
				// this.showFilter = false
			},
			submitsearch(formName) {
				let that = this
				this.$refs[formName].validate((valid, prop) => {
					// this.$refs[formName].clearValidate();
					let props = []
					for (let k in prop) {
						props.push(prop[k][0].field)

						if (prop[k][0].message = '注册时间不能为空') {
            if(that.submitTime) {
              if(	that.submitTime.length > 0	) {
                that.$refs[formName].clearValidate([prop[k][0].field])
                let timeIndex = props.indexOf('注册时间不能为空')
                props.splice(timeIndex, 1)
              }
							} else {
								return false
							}
						}
						if (prop[k][0].message = '离职时间不能为空') {
							if(that.updateTime) {
								if(	that.updateTime.length > 0	) {
									that.$refs[formName].clearValidate([prop[k][0].field])
									let timeIndex = props.indexOf('离职时间不能为空')
									props.splice(timeIndex, 1)
								}
							} else {
								return false
							}
						}
					}
					if (props.length) {
						that.$refs[formName].validateField(props, (valid2) => {
							if (valid2) {
								return false;
							} else {
								that.search()
							}

						})
					} else {
						that.search()
					}
				})
			},
			removeDomain(item) {
				this.showFilter = true
				delete this.paramsByUser[item.parameter]
				let index = this.conditionForm.condition.indexOf(item)
				if (index !== -1) {
					this.conditionForm.condition.splice(index, 1)
				}
				if (item.label === '注册时间') {
					this.submitTime = []
					delete this.paramsByUser.created_start_time
					delete this.paramsByUser.created_end_time
				}
				if (item.label === '离职时间') {
						this.updateTime = []
						delete this.paramsByUser.leaved_start_time
						delete this.paramsByUser.leaved_end_time
				}
				this.search()
			},
			changInput () {
				this.$refs['conditionForm'].clearValidate();
			},
			tableSortChange(column) {
				if (column.order === 'descending') {
					this.paramsByUser.sort_str = column.prop
					this.paramsByUser.sort_order = 'desc'
				} else if (column.order === 'ascending'){
					this.paramsByUser.sort_str = column.prop
					this.paramsByUser.sort_order = 'asc'
				} else {
					delete this.paramsByUser.sort_str
					delete this.paramsByUser.sort_order
				}

				this.loading = true;
				this.$axios.get('api/user/leaving', {
					params: this.paramsByUser
				})
				.then(res => {
					if (res.data.code == '200') {
						this.loading = false;
						this.tableData = res.data.data
						this.total = res.data.page.total
						this.pageSize = res.data.page.per_page;
						this.tableSize = res.data.page.per_page
						this.tableEnd = res.data.page.per_page;
					} else {
						this.$message.error('服务器繁忙')
					}
				})
			}
		},
		watch: {}
	};
</script>
<style lang='less' scoped>
	.outgoing {
    height: 100%; //撑满表格
    .el-table {
      width: 99.9% !important;
    }
  }
	.el-card {
		margin-bottom: 10px;
	}

	.el-main .ivu-poptip .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 450px;
		// height: 300px;
		overflow-y: scroll;
	}

	.el-main .poptip-condition .ivu-poptip-popper .ivu-poptip-content .ivu-poptip-inner {
		min-width: 180px;
	}

	.demo-dynamic {
		padding-left: 10px;

		.el-form-item {
			margin-bottom: 12px;
		}

		.el-input {
			width: 240px;
		}

		.el-date-editor {
			width: 240px;
		}

		.el-button {
			padding: 9px 15px;
			vertical-align: baseline;
		}

		.el-form-item__error {
			padding-top: 0;
		}
	}

	.poptip-condition {
		display: block;
		margin-top: 10px;

		.poptip-condition-item {
			line-height: 25px;
			cursor: pointer;
		}

		.poptip-condition-add {
			font-size: 14px;
		}
	}

	.btns {
		margin-top: 10px;
	}
</style>
